<!doctype html>
<html class="no-js" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">

    <title>Utbudstjänst - Väntetider</title>

    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <link rel="stylesheet" href="../css/font-awesome.css">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <link rel="stylesheet" href="../css/chosen.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/bootstrap-responsive.css">
    <link rel="stylesheet" href="../css/datepicker.css">
    <link rel="stylesheet" href="../css/tablesorter.css">
    <link rel="stylesheet" href="../css/ui-lightness/jquery-ui-1.8.21.custom.css">
    <link rel="stylesheet" href="../css/application-ocean-breeze.css">
    <link rel="stylesheet" href="../css/msgGrowl.css" type="text/css" charset="utf-8" />
    <link rel="stylesheet" href="../css/jquery.dataTables.css">
    <script src="../js/lib/modernizr-2.5.3.min.js"></script>

    <script id="subMasterTemplate" type="text/html">
        <div id="subMasterList">
            <table id="subMasterTable" cellpadding="0" class="table table-striped table-condensed table-hover dataTable">
                <thead>
                <tr>
                    <th width="23%" class="sortable">Åtgärd</th>
                    <th width="6%" class="sortable">Typ</th>
                    <th width="4%" class="text-center sortable">Normal</th>
                    <th width="4%" class="text-center sortable">Förtur</th>
                    <th width="5%" class="sortable">Gäller till</th>
                    <th width="4%">Info</th>
                    <th width="8%" class="text-center sortable">Ledig kapacitet</th>
                    <th width="4%" class="text-center">Status</th>
                </tr>
                </thead>
            </table>
        </div>
    </script>

    <script id="detailTemplate" type="text/html">

        <div id="hero10">
            <h2 class="closeable unmodified"><i class="icon-check-minus modified"></i><span id="title"></span></h2>
            <div class="row-fluid unmodified">
                <div class="alert">
                    <strong>Du har osparade ändringar!</strong> För att stänga raden måste du <a class="action-save">spara</a> eller <a class="action-cancel">avbryta</a>.
                </div>
            </div>
            <div id="form10" class="form-horizontal">

                <input id="productId" type="hidden"></input>

                <fieldset class="span5">
                    <legend>
                        <i class="icon-time"></i>
                        Väntetider
                    </legend>

                    <div id="waitTimes" class="control-group"></div>

                    <div class="control-group">
                        <label class="control-label">
                            <strong>Gäller till</strong>
                        </label>
                        <div class="controls">
                            <div class="input-append date datepicker" data-date-format="yyyy-mm-dd" data-date="">
                                <input id="validTo" class="input-small" type="text" placeholder="åååå-mm-dd" size="16"></input>
                                    <span class="add-on">
                                        <i id="datePicker10" class="icon-calendar" name="datePicker"></i>
                                    </span>
                            </div>
                        </div>
                    </div>

                </fieldset>

                <fieldset class="span6">
                    <legend>
                        <i class="icon-globe"></i>
                        Utomlänspatienter
                    </legend>

                    <div class="control-group">
                        <label class="control-label">
                            Ledig kapacitet
                        </label>
                        <div class="controls">
                            <label class="checkbox">
                                <select id="availableCapacity" class="listen-change">
                                    <option></option>
                                    <option value="true">Ja</option>
                                    <option value="false">Nej</option>
                                </select>
                            </label>
                        </div>
                    </div>

                    <div class="control-group">
                        <label class="control-label">
                            Kontaktinformation
                        </label>
                        <div class="controls">
                            <textarea id="referralInformation" class="input-xlarge" placeholder="Information till remittent för utomlänspatient." rows="4"></textarea>
                        </div>
                    </div>

                </fieldset>
            </div>
        </div>
        <!-- Actions Save & Cancel -->
        <div class="row-fluid actions-item">
            <div class="span12 unmodified">
                <div class="pull-right">
                    <button class="btn action-cancel"><i class="icon-remove"></i> Avbryt</button>
                    <button class="btn btn-primary action-save" disabled="disabled"><i class="icon-thumbs-up"></i> Spara</button>
                </div>
            </div>
        </div>
    </script>

    <script id="waitTimeTemplate" type="text/html">
        <div class="waitTimeBlock">
            <input id="codeSystem" type="hidden"></input>
            <input id="waitTimeCode" type="hidden"></input>
            <input id="waitTimePriorityCode" type="hidden"></input>

            <div class="control-group">
                <label class="control-label">
                    <strong id="waitTimeName"></strong>
                </label>
                <div class="controls">
                    <div>
                        <input id="waitTime" class="input-mini" type="text"></input>
                        <small>veckor</small>
                    </div>
                </div>
            </div>

            <div class="control-group">
                <label class="control-label">
                    <small>med förtur</small>
                </label>
                <div class="controls">
                    <div>
                        <input id="waitTimePriority" class="input-mini" type="text"></input>
                        <small>veckor</small>
                    </div>
                </div>
            </div>
        </div>
    </script>

</head>

<body>

<div id="capacity-view" class="wrapper">
    <div id="headerPlaceholder"></div>

    <div id="content">
        <div class="container">

            <div class="row">
                <div class="span12" id="list">
                    <table id="masterTable" cellpadding="0" class="table table-striped table-hover dataTable">
                        <thead>
                        <tr>
                            <th width="40%" class="sortable">Enhet</th>
                            <th width="60%" class="sortable">HSA-ID</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>

                <!-- Legend -->

                <div id="legend" class="help-block pull-right span12" style="margin-top:36px;">
                            <span class="pull-right">
                                <i class="icon-ok" style="color:green"></i> Väntetiden OK
                            </span>
                            <span class="pull-right clear">
                                <i class="icon-exclamation" style="margin-left:12px;"></i> Väntetiden går snart ut
                            </span>
                            <span class="pull-right clear">
                                <i class="icon-warning-sign" style="color:red"></i> Väntetiden är inte giltig längre
                            </span>
                </div>

            </div> <!-- /.row -->

        </div> <!-- /.container -->

    </div> <!-- /#content -->

</div> <!-- /#wrapper -->



<script src="../js/lib/jquery-1.7.2.min.js"></script>
<script src="../js/lib/jquery-ui-1.8.21.custom.min.js"></script>
<script src="../js/lib/jquery.ui.touch-punch.min.js"></script>
<script src="../js/lib/bootstrap.min.js"></script>
<script src="../js/lib/bootstrap-datepicker.js"></script>
<script src="../js/lib/jquery.tablesorter.min.js"></script>
<script src="../js/lib/moment.min.js"></script>
<script src="../js/lib/jquery.dataTables.js"></script>
<script src="../js/lib/jquery.validate.js"></script>
<script src="../js/lib/chosen.jquery.min.js"></script>
<script src="../js/lib/msgGrowl.min.js"></script>
<script src="../js/lib/jquery.cookie.js"></script>
<script src="../js/lib/jquery-handlebars-1.1.4.min.js"></script>
<script src="../js/md.js"></script>
<script src="../js/common.js"></script>

<script>
            commonInit({
                tabCapacity: true,
                viewDataUrl: '../rest/view/capacity',
                mastheadTitle: 'Väntetider'
            });

            $("#masterTable").MasterDetail({
                masterData: viewData.capacity,
                masterColumns: [
                    {
                        mData:      'name',
                        mRender:    renderUnitName
                    },
                    {
                        mData:      'name',
                        mRender:    renderHSA
                    }
                ],
                detailTemplateId: 'subMasterTemplate',
                initDetail: initSubMaster,
                validateDetail: validateDetail,
                openDetailCallback: function(dt, row, container) {
                    // Hack to remember the root master row
                    container.rootRow = row;
                }
            });

            // If the table is small enough, hide the search bar
            if (viewData.capacity.length > 100) {
              $('#masterTable_filter').show();
            } else {
              $('#masterTable_filter').hide();
            }

            function initSubMaster(container, data) {
                var rootRow = container.rootRow;
                var subMasterTable = setUniqueId($('#subMasterTable', container));
                subMasterTable.MasterDetail({
                	masterTable: subMasterTable,
	                masterData: data.products,
	                masterColumns: [
	                    {
	                        mData:      'name',
	                        mRender:    MasterDetail.renderString
	                    }, {
	                        // capacities[n].shortDisplayName
	                        // Handled in masterDrawCallback()
	                        sDefaultContent: ''
	                    }, {
                            // capacities[n].waitTime
                            // Handled in masterDrawCallback()
	                        sDefaultContent: ''
	                    }, {
                            // capacities[n].waitTimePriority
                            // Handled in masterDrawCallback()
	                        sDefaultContent: ''
	                    }, {
	                        mData:      'validTo',
	                        mRender:    MasterDetail.renderDate
	                    }, {
	                        mData:      'referralInfo',
                            mRender:    MasterDetail.renderString
	                    }, {
	                        mData:      'availableCrossRegionCapacity',
	                        mRender:    renderYesNoFromEnum
	                    }, {
	                        mData:      'status',
	                        mRender:    renderStatus
	                    }
	                ],
	                initDetail: initDetail,
	                updateDetail: function(subContainer) {
	                    return updateDetail(subContainer, data.hsaID, rootRow);
	                },
	                masterDrawCallback: masterDrawCallback,
	                openDetailCallback: openDetailCallback,
                    masterPaginate: false,
                    masterFilter: false,
                    masterInfo: false,
                    selectedRowClass: 'hidden'
	            });
            }

            // Post-processes the table DOM created by DataTables to handle multi-row cells
            function masterDrawCallback(dt) {
                var rows = dt.fnGetNodes();
                $.each(rows, function(rowNum, row) {
                    var data = dt.fnGetData(row);
                    var newRows = [];
                    $.each(data.capacities, function(dataRowNum, capacity) {
                        var columnContent = [];

                        columnContent[1] = MasterDetail.renderString(capacity.shortDisplayName);
                        columnContent[2] = renderWeeks(capacity.waitTime);
                        columnContent[3] = renderWeeks(capacity.waitTimePriority);

                        if (dataRowNum == 0) {
                            // First row - modify existing cells
                            var rowSpan = data.capacities.length;
                            $(row.cells[4]).removeClass('status-expired');
                            $(row.cells[4]).removeClass('status-ok');
                            $(row.cells[7]).removeClass('status-expired');
                            $(row.cells[7]).removeClass('status-ok');
                            $(row.cells[4]).addClass('status-' + data.status.toLowerCase());
                            $(row.cells[7]).addClass('status-' + data.status.toLowerCase());

                            $('td', row).each(function(colNum) {
                                var cell = $(this);
                                if (columnContent[colNum]) {
                                    cell.html(columnContent[colNum]);
                                } else {
                                    // cell.attr('rowspan', rowSpan);
                                }
                            });
                        } else {
                            // Create extra row
                            var newRow = row.cloneNode();

                            $(newRow).addClass('countme-in');
                            $(newRow).append('<td>&nbsp;</td>')
                            for (colNum in columnContent) {
                                $(newRow).append('<td>' + columnContent[colNum] + '</td>');
                            }
                            $(newRow).append('<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>')
                            newRows.push(newRow);
                        }
                    });
                    // Insert extra rows into DOM
                    $(row).after(newRows);
                });
            }

            // DataTables doesn't know about rowspan and will insert
            // the detail <tr> right after the first master <tr>, which is
            // wrong if the master row spans multiple <tr>'s.
            // This ugly hack moves the detail <tr> to the correct position.
            function openDetailCallback(dt, row, detail) {
                var rows = dt.$('tr', {filter: 'applied', order: 'current', page: 'current'});
                var nextIndex = $.inArray(row, rows) + 1;
                if (nextIndex < rows.length) {
                    $(detail).detach().insertBefore(rows[nextIndex]);
                } else {
                    // Last row
                    $(detail).detach().appendTo($(row).parent());
                }
            }

            function initDetail(container, data) {
                $('#title', container).html(data.name);

                $('#productId', container).val(data.id);

                $.each(data.capacities, function(i, capacity) {
                    var waitTime = $($('#waitTimeTemplate').html());
                    $('#waitTimeName', waitTime).html(capacity.longDisplayName);
                    $('#codeSystem', waitTime).val(capacity.codeSystem);
                    $('#waitTimeCode', waitTime).val(capacity.waitTimeCode);
                    $('#waitTimePriorityCode', waitTime).val(capacity.waitTimePriorityCode);

                    var waitTimeInput = $('#waitTime', waitTime);
                    waitTimeInput.prop('disabled', !capacity.waitTimeActive);
                    waitTimeInput.val(capacity.waitTime);

                    var waitTimePriorityInput = $('#waitTimePriority', waitTime);
                    waitTimePriorityInput.prop('disabled', !capacity.waitTimePriorityActive);
                    waitTimePriorityInput.val(capacity.waitTimePriority);

                    $('#waitTimes', container).append(waitTime);
                });

                if (data.validTo) {
                    $('#validTo', container).val($.datepicker.formatDate('yy-mm-dd', new Date(data.validTo)));
                }

                var availableCapacityInput = $('#availableCapacity', container); 
                availableCapacityInput.prop('disabled', !data.availableCrossRegionCapacityActive);
                var mappedCapacity;
                if (data.availableCrossRegionCapacity === 'YES') {
                    mappedCapacity = 'true';
                } else if (data.availableCrossRegionCapacity === 'NO') {
                    mappedCapacity = 'false';
                }

                availableCapacityInput.val(mappedCapacity);

                var referralInformationInput = $('#referralInformation', container);
                referralInformationInput.prop('disabled', !data.referralInfoActive);
                referralInformationInput.val(data.referralInfo);

                $('.datepicker', container).datepicker({autoclose: true, dateFormat: 'yy-mm-dd'});
                availableCapacityInput.chosen({
                    placeholder_text_single: 'Välj...',
                    disable_search_treshold: 10
                });
            }

            function updateDetail(container, unitId, rootRow) {
                var capacities = [];
                $('.waitTimeBlock', container).each(function(i, waitTimeBlock) {
                    var capacity = {
                        codeSystem: $('#codeSystem', waitTimeBlock).val(),
                        waitTimeCode: $('#waitTimeCode', waitTimeBlock).val(),
                        waitTime: $('#waitTime', waitTimeBlock).val(),
                        waitTimePriorityCode: $('#waitTimePriorityCode', waitTimeBlock).val(),
                        waitTimePriority: $('#waitTimePriority', waitTimeBlock).val()
                    };
                    capacities.push(capacity);
                });

                var availableCrossRegionCapacity = $('#availableCapacity', container).val();
                if (availableCrossRegionCapacity === '') {
                    availableCrossRegionCapacity = null;
                } else if (availableCrossRegionCapacity === 'true') {
                    availableCrossRegionCapacity = 'YES';
                }  else if (availableCrossRegionCapacity === 'false') {
                    availableCrossRegionCapacity = 'NO';
                }

                var productId = $('#productId', container).val();
                var data = {
                    capacity: [{
                        hsaID: unitId,
                        products: [{
                            id: productId,
                            availableCrossRegionCapacity: availableCrossRegionCapacity,
                            referralInfo: $('#referralInformation', container).val(),
                            validTo: $.datepicker.parseDate('yy-mm-dd', $('#validTo', container).val()).getTime(),
                            capacities: capacities
                        }]
                    }]
                };

                var retData = false;
                $.ajax({
                    url: '../rest/view/capacity',
                    type: 'PUT',
                    data: JSON.stringify(data),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(data) {
                        showGrowlMessage('Väntetid uppdaterad.');
                        var retUnit = data[0];  // Can only be one unit in response
                        retData = $.grep(retUnit.products, function(product) {
                            return product.id === productId;
                        })[0];
                        // Also update root masterDetail
                        $("#masterTable").dataTable().fnUpdate(retUnit, rootRow);
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(textStatus + "<br />" + errorThrown);
                        if (textStatus==='error' && errorThrown==='Unauthorized') {
                            alert("Din användarsession har gått ut, du måste logga in på nytt!")
                            $(location).attr('href','../');
                        }
                    }
                });
                console.log('retData:');
                console.log(retData);
                return retData;
            }

             /**
             * Validates form
             * 
             * @param {type} container
             * @returns {true or false}
             */
            function validateDetail(container) {
                return true;
            }
 
            function renderUnitName(data, type, full) {
                var name = data ? data : "Namn saknas";
                // name += " (" + full.hsaID + ")";
                return MasterDetail.renderClosable(name, type, full);
            }

            function renderHSA(data, type, full) {
                var name = '';
                name += full.hsaID + "";
                return MasterDetail.renderClosable(name, type, full);
            }

            function renderYesNoFromEnum(data, type, full) {
                return data === 'YES' ? 'Ja' : 'Nej';
            }

            function renderWeeks(data, type, full) {
                return MasterDetail.renderString(data ? (data + ' v') : '-');
            }

            function renderStatus(data, type, full) {
                if (data === 'OK') {
                    return '<i class="icon-ok" style="color:green"></i>';
                } else if (data === 'EXPIRING') {
                    return '<i class="icon-exclamation"></i>';
                } else {
                    return '<i class="icon-warning-sign"></i>';
                }
            }
        </script>

</body>
</html>
